<template>
  <div class="container">
    <div class="header">
      <el-input v-model="listQuery.keyword" placeholder="请输入机构名称、校长名字、服务电话" class="filter-item" clearable @keyup.enter.native="handleFilter" />
      <label class="form-key handleDistance">机构状态：</label>
      <el-select v-model="listQuery.status" placeholder="请选择状态" clearable class="filter-item">
        <el-option label="全部" value="0" />
        <el-option label="上架" value="2" />
        <el-option label="下架" value="3" />
      </el-select>
      <label class="form-key handleDistance">区域范围：</label>
      <el-cascader
        size="large"
        :options="areaOptions"
        @change="areaChange"
      />
      <el-checkbox v-model="listQuery.isCertified" class="filter-item" style="margin-left:15px;">
        是否认证
      </el-checkbox>
      <el-button icon="el-icon-search" size="small" type="primary" class="handleDistance" @click="handleFilter">查询</el-button>
      <!--      <el-button  style="margin-left: 10px;" type="primary" icon="el-icon-upload2" @click="handleExcelDownload">-->
      <!--        导出Excel-->
      <!--      </el-button>-->
      <!--      <el-button  type="primary" icon="el-icon-download" @click="dialogTemplateVisible = true">-->
      <!--        导入商户-->
      <!--      </el-button>-->
      <!--      <label class="form-key" style="margin-left: 10px;color:#1890ff;" @click="handleExcelDownloadTemplate">下载导入模板</label>-->
      <!--      <el-button v-show="checkPermission('merchantAdd')"  type="primary" icon="el-icon-plus" style="float:right" @click="handleAdd">-->
      <!--        新增商户-->
      <!--      </el-button>-->
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      style="width: 100%;"
      :element-loading-text="g.loadingStr"
      :header-cell-style="{background:g.mainColor}"
    >
      <el-table-column label="序号" align="center" fixed width="50">
        <template slot-scope="{$index}">
          <span>{{ $index + 1 + ( listQuery.currentPage - 1 ) * listQuery.pageSize }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商户LOGO" align="center" width="150">
        <template slot-scope="{row}">
          <span><img :src="row.logoImg" class="table-row-img"></span>
        </template>
      </el-table-column>
      <el-table-column label="商户小图标" align="center" width="100">
        <template slot-scope="{row}">
          <span v-if="row.icon"><img :src="row.icon" class="small-row-logo"></span>
        </template>
      </el-table-column>
      <el-table-column label="机构名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机构地址" align="center">
        <template slot-scope="{row}">
          <span>{{ row.detail }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商户负责人" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{ row.principalName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" width="120px">
        <template slot-scope="{row}">
          <span>{{ row.serverPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="经营范围" align="center">
        <template slot-scope="{row}">
          <span>{{ row.categoryNames }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入驻时间" align="center" width="140">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否参与活动" align="center" width="110">
        <template slot-scope="{row}">
          <span style="display:flex;justify-content: center;align-items: center;margin-right:10px">
            <i :class="row.isJoin===0?'el-icon-close':'el-icon-check'" :style="row.isJoin===0?'color:red':'color:green'" />
            <span>{{ row.isJoin===0?'未参与':'已参与' }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="220">
        <template slot-scope="{row}">
          <el-button v-show="checkPermission('merchantEdit')" type="primary" size="mini" @click="handleUpdate(row)">
            修改资料
          </el-button>
          <el-button v-show="checkPermission('merchantCourseList')" type="success" size="mini" @click="handleCheckCourse(row)">
            查看课程
          </el-button>
          <p />
          <el-button v-if="row.status === 2" type="danger" size="mini" @click="handleStatus(row)">
            商户下架
          </el-button>
          <el-button v-else-if="row.status === 3" type="danger" size="mini" @click="handleStatus(row)">
            商户上架
          </el-button>
          <el-button type="warning" size="mini" @click="handleIsJoinActivities(row)">
            {{ row.isJoin===0?'参与活动':'取消活动' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog
      title="提示"
      :visible.sync="dialogTemplateVisible"
      width="30%"
    >
      <el-upload
        class="upload-demo"
        action="#"
        :limit="1"
        :auto-upload="false"
        :on-change="handleExcelFileChange"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTemplateVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleExcelUpload">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { regionDataPlus, CodeToText } from 'element-china-area-data'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { urlEncode } from '@/utils'
import axios from 'axios'
import { merchantList, merchantStatus, isJoinaActivity } from '@/api/account'
import { getToken } from '@/utils/auth'

export default {
  name: 'MerchantList',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        keyword: '',
        isCertified: true,
        status: '2',
        province: '',
        city: '',
        region: '',
        town: ''
      },
      areaOptions: regionDataPlus,
      dialogTemplateVisible: false,
      excelFile: null
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      const data = {}
      for (const item of Object.keys(this.listQuery)) {
        data[item] = this.listQuery[item]
      }
      data['isCertified'] = data['isCertified'] ? 1 : 0
      data['province'] = data['province'] === '全部' ? '' : data['province']
      merchantList(data).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.currentPage = 1
      this.getList()
    },
    areaChange(value) {
      const provinces = CodeToText[value[0]]
      const city = CodeToText[value[1]]
      const region = CodeToText[value[2]]
      const town = CodeToText[value[3]]
      this.listQuery.province = provinces
      this.listQuery.city = city === undefined || city === '全部' ? '' : city
      this.listQuery.region = region === undefined || region === '全部' ? '' : region
      this.listQuery.town = town === undefined || town === '全部' ? '' : town
      console.log(this.listQuery)
    },
    handleAdd() {
      this.$router.push('MerchantAdd')
    },
    handleStatus(row) {
      const text = row.status === 3 ? '上架' : '下架'
      this.$confirm('是否确认' + text + '该商户？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(JSON.stringify(this.multipleSelection))
        merchantStatus({
          businessId: row['id'],
          status: row.status === 3 ? 2 : 3
        }).then(response => {
          this.$message({ message: '操作成功', type: 'success' })
          this.getList()
        })
      })
    },
    handleUpdate(row) {
      this.$router.push({ name: 'MerchantEdit', params: { id: row.id }})
    },
    handleCheckCourse(row) {
      this.$router.push({ name: 'MerchantCourseList', params: { id: row.id }})
    },
    handleExcelDownload() {
      const data = new Map()
      for (const key of Object.keys(this.listQuery)) {
        data[key] = this.listQuery[key] == null ? '' : this.listQuery[key]
      }
      delete data['currentPage']
      delete data['pageSize']

      window.location.href = process.env.VUE_APP_BASE_API + 'jbl-business/api/admin/v1/business/export?' + urlEncode(data).slice(1)
    },
    handleExcelDownloadTemplate() {
      window.location.href = 'http://ossdev0.oss-cn-shenzhen.aliyuncs.com/%E5%AF%BC%E5%85%A5%E5%95%86%E6%88%B7%E6%A8%A1%E6%9D%BF.xlsx'
    },
    handleExcelFileChange(file, fileList) {
      this.excelFile = fileList.length > 0 ? file : null
    },
    handleExcelUpload() {
      console.log(this.excelFile)
      const param = new FormData()
      param.append('file', this.excelFile.raw, this.excelFile.name)
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Access-Control-Allow-Origin': '*',
          'x-access-token': getToken()
        }
      }
      axios.post(process.env.VUE_APP_BASE_API + this.g.excelUpload.substr(1), param, config)
        .then(response => {
          console.log('提交成功')
          console.log(response)
          if (response.data.successCount === response.data.total) {
            this.$message({ message: '操作成功', type: 'success' })
            this.getList()
          } else {
            this.$message({ message: '操作失败,请查看下载文件', type: 'error' })
            window.location.href = process.env.VUE_APP_BASE_API + 'jbl-business/api/admin/v1/business/downloadErrors?fileName=' + response.data.errorsFile
          }
          this.dialogTemplateVisible = false
        })
    },
    // 是否参与活动
    handleIsJoinActivities(row) {
      const tipsInfo = row.isJoin === 0 ? '是否确定参与活动' : '是否确定取消该机构活动'
      const joinStatus = row.isJoin === 0 ? 1 : 0
      this.$confirm(`${tipsInfo}`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const activitiesParams = {
          businessId: row.id,
          isJoin: joinStatus
        }
        isJoinaActivity(activitiesParams).then(res => {
          if (res.code === '200') {
            this.$message({
              message: '设置成功',
              type: 'success'
            })
            this.getList()
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container{
  padding: 15px;
  .header{
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  .el-input{
    width: 240px;
  }
  .handleDistance{
    margin-left: 15px;
  }
}
.table-row-img{
  width:80px;
  height: 80px;
  object-fit: contain;
}
/deep/ .el-table_1_column_11 .cell .el-button{
  margin: 5px;
}
.small-row-logo{
  width: 50px;
  height: 50px;
}
</style>
